window.__modules__ = window.__modules__ || {};

/**
 * Loads a JavaScript file and returns a Promise for when it is loaded
 * @param {*} url 
 * @return Promise
 */
export const loadScript = url => {
    return new Promise((resolve, reject) => {
        const version = localStorage.getItem('__v__') || '1.0.0';
        const urlId = `${url}_${version}`;
        const success = {code: 200};
        const failuire = {code: 500};

        if(__modules__[urlId]){
            resolve(success);
            return;
        }

        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.crossorigin = 'anonymous';
        const removeEvents = () => {
            script.onerror = null;
            script.onload = null;
            document.head.removeChild(script);
        }

        // IE
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState === 'loaded' || script.readyState === 'complete') {
                    script.onreadystatechange = null;
                    script.onerror = null;
                    document.head.removeChild(script);
                    __modules__[urlId] = true;
                    resolve(success);
                }
            }
        }else {
            script.onload = () => {
                removeEvents();
                __modules__[urlId] = true;
                resolve(success);
            }
        }
        if(script.onerror){
            script.onerror = () => {
                removeEvents();
                reject(failuire);
            };
        }

        script.src = url;
        document.head.appendChild(script);
    })
}